package com.jthinker.base.utils;

import com.jthinker.base.constant.Constant;
import com.jthinker.bean.UserWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.fluent.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.jthinker.base.constant.Constant.*;

/**
 * Created by chen.gang on 2014/12/20.
 */
public class SSOUtils
{
    
    private static final Logger LOGGER= LoggerFactory.getLogger(SSOUtils.class);

    /**
     * 加入缓存,注销用
     *
     * @param st
     * @param tgt
     * @param url
     */
    public static void addLogoutST(String st, String tgt, String url)
    {
        Long userId = CacheUtils.get(TICKET_CACHE_NAME, tgt);
        if (userId == null)
        {
            return;
        }

        Map<String, String> map = CacheUtils.get(LOGOUT_CACHE, userId);

        if (map == null)
        {
            map = new HashMap<String, String>();
            Map<String, String> _map = CacheUtils.add(LOGOUT_CACHE, userId, map);
            if (_map != null)
            {
                map = _map;
            }
            else
            {
                map = CacheUtils.get(LOGOUT_CACHE, userId);
            }
        }

        System.out.println(map == CacheUtils.get(LOGOUT_CACHE, userId));
        synchronized (map)
        {
            map.put(url, st);
        }

    }

    public static void addST2Cache(String st, String tgt)
    {
        CacheUtils.add(TICKET_CACHE_NAME, st, tgt);
    }

    /**
     * 注销
     *
     * @param tgt
     * @return
     */
    public static boolean invalidateTGT(String tgt)
    {
        Long userId = CacheUtils.get(TICKET_CACHE_NAME, tgt);
        Map<String, String> map = CacheUtils.get(LOGOUT_CACHE, userId);

        if (map == null || map.isEmpty())
        {
            return true;
        }

        for (Map.Entry<String, String> entry : map.entrySet())
        {
            String basePath = WebUtils.getUrlBasePath(entry.getKey());
            String logoutUrl = basePath + LOG_OUT_BROADCAST;
            try
            {
                Request.Post(new StringBuilder(logoutUrl).append("?").append(ST).append("=").append(entry.getValue()).toString()).execute();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                LOGGER.error("Exception: {}", e);
            }
        }

        return CacheUtils.remove(LOGOUT_CACHE, userId)
                && CacheUtils.remove(TICKET_CACHE_NAME, userId)
                && CacheUtils.remove(TICKET_CACHE_NAME, tgt)
                && CacheUtils.remove(USER_CACHE_NAME, userId);
    }

    /**
     * 将TGT加入缓存
     *
     * @param tgt
     * @param user
     * @return
     */
    public static String addTGT2Cache(String tgt, UserWrapper user)
    {
        long userId = user.getId();
        String _tgt = CacheUtils.add(TICKET_CACHE_NAME, userId, tgt);
        if (StringUtils.isNotEmpty(_tgt))
        {
            return _tgt;
        }

        CacheUtils.add(TICKET_CACHE_NAME, tgt, userId);
        CacheUtils.add(USER_CACHE_NAME, userId, user);

        return null;
    }

    public static String getTGT(String tgc)
    {
        return CacheUtils.get(TICKET_CACHE_NAME, tgc);
    }

    public static void addTGC2Cache(String tgc, String tgt)
    {
        CacheUtils.add(TICKET_CACHE_NAME, tgc, tgt);
    }

    public static String generateTGC()
    {
        return TGC + "_" + getUUID();
    }

    public static String generateTGT()
    {
        return TGT + "_" + getUUID();
    }

    public static String generateST()
    {
        return ST + "_" + getUUID();
    }

    public static String getUUID()
    {
        return StringUtils.replace(UUID.randomUUID().toString(), "-", "");
    }
}
